<?php

session_start();
include('../include/dbFunctions.php');

//Setup variables
if(isset($_GET['id'])) {

    $deleteID = $_GET['id'];

//$deleteID = $_SESSION['id'];
    $ContactTable = "contact_school";
    $SchoolTable = "school";
    $primary_key = "school_id";

    $queryEvent = "SELECT * FROM event WHERE school_id=$deleteID";
    $event=executeSelectQuery($queryEvent);
    $numevent=count($event);

    if($numevent==0) {
        //Delete contact from school first
        $query1 = "DELETE FROM $ContactTable WHERE $primary_key = $deleteID";
        $result1 = executeQuery($query1);

        //Delete school secondly
        $query2 = "DELETE FROM $SchoolTable WHERE $primary_key = $deleteID";
        $result2 = executeQuery($query2);
        if($result2!=0) {
            $_SESSION['mes'] = "Your record has been deleted successfully";
        }else {
            $_SESSION['mes'] = "Error! Please try again";
        }
        header('Location: schoolManage.php');

    }else {
        $_SESSION['mes'] = "Cannot delete this school because there is related event.";
        header('Location: schoolManage.php');
    }
} elseif(isset($_POST['id_school'])) {
    //Delete contact from school first
    $id_school=$_POST['id_school'];
    for ($i=0;$i<count($id_school);$i++) {
        $queryEvent = "SELECT * FROM event WHERE school_id=$id_school[$i]";
        $event=executeSelectQuery($queryEvent);
        $numevent=count($event);
        if($numevent==0) {
            $uQuery= "DELETE FROM school
        WHERE school_id='".$id_school[$i]."'";
            $uResult = executeQuery($uQuery);
            if ($uResult!=0) {
                $_SESSION['mes'] = "Your record has been deleted successfully";
            }else {
                $_SESSION['mes'] = "Error! Please try again";
            }
        } else {
            $_SESSION['mes'] = "Cannot delete this school because there is related event.";
        }
    }
} else {
    $_SESSION['mes'] = "You must choose at least 1 record to delete.";
    header('Location: schoolManage.php');
}
header('Location: schoolManage.php');

?>
